﻿using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using ZP.Common;
using ZP.DTO.Common;
using ZP.DTO.fz_base_param;
using ZP.IBLL;
using ZP.IDAL;
using ZP.Model;
using Z.EntityFramework.Plus;

namespace ZP.BLL
{
    public class fz_base_paramService : BaseService<fz_base_param, int>, Ifz_base_paramService
    {
        //public fz_base_paramService(Ifz_base_paramDAL _fz_base_paramDAL, Ifz_base_employeeDAL _fz_base_employeeDAL)
        //{
        //    this._fz_base_paramDAL = _fz_base_paramDAL;
        //    this._fz_base_employeeDAL = _fz_base_employeeDAL;

        //    this._repository = _fz_base_paramDAL;
        //}

        /// <summary>
        /// 获得所有的参数信息
        /// </summary>
        /// <returns></returns>
        public PageModel<fz_base_paramResultDTO> GetBaseParam(fz_base_paramSearchDTO dto, bool isPaging = true)
        {
            PageModel<fz_base_paramResultDTO> result = new PageModel<fz_base_paramResultDTO>();
            List<fz_base_param> resultDTO = new List<fz_base_param>();
            Expression<Func<fz_base_param, bool>> WhereLambda = (p => p.state == ZPFlagType.YES);
            //这里可以优化，参照FZ_Base_RepoServices
            if (isPaging)
            {
                if (!string.IsNullOrWhiteSpace(dto.SearchText))
                {
                    WhereLambda = WhereLambda.And(p => p.name.Contains(dto.SearchText));
                }
                if (!string.IsNullOrWhiteSpace(dto.type))
                {
                    WhereLambda = WhereLambda.And(p => p.type == dto.type);
                }
                int total = 0;
                Expression<Func<fz_base_param, int>> OrderByLambda = (o => o.id);
                var iquery = _repository.GetModelsByPage(dto.limit, dto.page, out total, WhereLambda, OrderByLambda, false);

                result.count = total;
                resultDTO = iquery.ToList();
            }
            else
            {
                var iquery = _repository.GetModels(p => p.state == ZPFlagType.YES);
                if (!string.IsNullOrWhiteSpace(dto.type))
                {
                    int total = 0;
                    switch (dto.type.ToUpper())
                    {
                        case "TYPE":    //参数类别-查询所有
                            List<string> typeList = iquery.GroupBy(p => p.type).Select(o => o.Key).ToList();//.Select(o=> new fz_base_param { type = o });
                            total = typeList.Count();
                            resultDTO = typeList.Select(p => new fz_base_param { type = p }).ToList();
                            break;
                        #region 参数名称-根据参数类别查询所有
                        case ZPBaseType.EMPLOYEE_TYPE:
                        case ZPBaseType.GOODS_TYPE:
                        case ZPBaseType.GOODS_UNIT:
                        case ZPBaseType.MATERIAL:
                        case ZPBaseType.GOODS_STANDARD:
                        case ZPBaseType.GOODS_MODEL:
                        case ZPBaseType.COLOR:
                        case ZPBaseType.BRAND:
                            iquery = iquery.Where(p => p.type == dto.type);
                            total = iquery.Count();
                            iquery = iquery.OrderBy(m => m.id);
                            resultDTO = iquery.ToList();
                            break;
                        #endregion
                        default:
                            throw new Exception(TipsMessage.没有该参数类别);
                    }
                    result.count = total;
                }
                else
                {
                    result.count = iquery.Count();
                    iquery = iquery.OrderBy(m => m.id);
                    resultDTO = iquery.ToList();
                }
            }
            result.data = Mapper.Map<List<fz_base_param>, List<fz_base_paramResultDTO>>(resultDTO);
            return result;
        }

        /// <summary>
        /// 保存基础参数-新增/修改
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public bool SaveBaseParam(fz_base_paramOperateDTO dto)
        {
            bool result = false;
            if (0 == dto.id || !dto.id.HasValue)
            {
                //判断是否已经存在相同名称和类别的参数
                bool existsCount = _repository.GetModels(p => p.name == dto.name && p.type == dto.type).Any();
                if (existsCount)
                {
                    throw new Exception(TipsMessage.该类别的名称已存在);
                }

                //新增
                var item = Mapper.Map<fz_base_paramOperateDTO, fz_base_param>(dto);
                item.state = 1;
                item.createtime = DateTime.Now;
                _repository.Add(item, false);
                //Add(psie, item);

                // 记录日志
                //this.AddLog(psie, new LogData
                //{
                //    CurrentLogType = LogType.ADD,
                //    LogDetails = "新增基础参数" + dto.type + "," + dto.name,
                //    OpratorName = dto.creater
                //});
            }
            else
            {
                //判断是否已经存在角色名称和角色编码
                bool existsCount = _repository.GetModels(p => p.name == dto.name && p.type == dto.type && p.id != dto.id).Any();
                if (existsCount)
                {
                    throw new Exception(TipsMessage.该类别的名称已存在);
                }

                //修改
                fz_base_param item = _repository.Find(dto.id.Value);
                dto.state = ZPFlagType.YES;
                dto.createtime = DateTime.Now;
                Mapper.Map<fz_base_paramOperateDTO, fz_base_param>(dto, item);

                _repository.Update(item, false);
                //Modify(psie, item);

                // 记录日志
                //this.AddLog(psie, new LogData
                //{
                //    CurrentLogType = LogType.MODIFY,
                //    LogDetails = "修改基础参数" + dto.type + "," + dto.name,
                //    OpratorName = dto.creater
                //});
            }
            result = _repository.SaveChanges();

            return result;
        }

        /// <summary>
        /// 删除基础参数
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public bool DeleteBaseParam(List<fz_base_paramOperateDTO> dto, UserLoginDTO loginUser)
        {
            bool result = false;
            if (dto == null || dto.Count == 0)
            {
                return result;
            }
            var ids = dto.Where(p => p.id.HasValue).Select(s => s.id.Value).ToList();
            if (ids.Count == 0)
            {
                return result;
            }
            List<string> existList = new List<string>();
            int[] notDelIds = { 1, 2, 3, 4 };
            //半成品-成品-零配件-原材料 商品类别不能删除
            var ids_jiaoji = ids.Intersect(notDelIds.ToList()).ToList();
            if (ids_jiaoji.Count > 0)
            {
                existList = dto.Where(p => p.id.HasValue && ids_jiaoji.Contains(p.id.Value)).Select(s => s.name).ToList();
                throw new Exception(string.Format(TipsMessage.该参数类别名称还有商品在使用, string.Join(",", existList)));
            }

            //查询参数类别名称是否有商品在使用，存在则不能删除
            var typeList = dto.Distinct().Select(p => p.type).ToList();
            bool existsCount = false;

            if (!existsCount)
            {
                existList = _fz_base_employeeDAL.GetModels(p => typeList.Contains(p.type)).Select(s => s.type).ToList();
                existList = dto.Where(p => existList.Contains(p.type)).Select(s => s.name).ToList();
                existsCount = existList.Any();
            }
            if (!existsCount)
            {
                existList = _repository.GetModels(p => typeList.Contains(p.type)).Select(s => s.name).ToList();
                existsCount = existList.Any();
            }

            if (existsCount)
            {
                throw new Exception(string.Format(TipsMessage.该参数类别名称还有商品在使用, string.Join(",", existList)));
            }
            var iquery = _repository.GetModels(p => ids.Contains(p.id));
            //var deleteCount = iquery.Update(p => new fz_base_param() { state = ZPFlagType.NO }); //逻辑删除
            int deleteCount = _repository.Delete(ids.ToArray());  //物理删除

            // 记录日志
            //this.AddLog(psie, new LogData
            //{
            //    CurrentLogType = LogType.DELETE,
            //    LogDetails = "删除基础参数" + dto.name + "," + dto.type,
            //    OpratorName = dto.creater
            //});
            result = deleteCount > 0;

            return result;
        }
    }
}
